package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.Backtracking;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全排列
 * https://leetcode.com/problems/permutations/
 *
 * @author tzp
 * @since 2020/10/16
 */
public class LC46 implements Backtracking {
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        if (nums == null || nums.length == 0) return Collections.emptyList();
        //本来想用Bitset, 发现需要顺序所以改成list, 其实用LinkedHashedSet比较好.
        List<Integer> path = new ArrayList<>();
        backtracking(nums, path, nums.length);
        return result;
    }

    public void backtracking(int[] nums, List<Integer> path, int remainLength) {
        if (remainLength == 0) {
            result.add(path.stream().map(i -> nums[i])
                    .collect(Collectors.toList()));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (!path.contains(i)) {
                    path.add(new Integer(i));//mark used
                    backtracking(nums, path, remainLength - 1);
                    path.remove(new Integer(i));//mark unused
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new LC46().permute(new int[]{1, 2, 3}));
    }
}
